//
//  UploadImageViewController.m
//  Kjs-iOS
//
//  Created by 江伟 on 16/8/2.
//  Copyright © 2016年 jmhz. All rights reserved.
//

#import "UploadImageViewController.h"
#import "KJSRequest.h"
#import "ImageCollectionViewCell.h"
#import "LastCollectionViewCell.h"
#import <AssetsLibrary/ALAsset.h>
#import <AssetsLibrary/ALAssetsLibrary.h>
#import <AssetsLibrary/ALAssetsGroup.h>
#import <AssetsLibrary/ALAssetRepresentation.h>

@interface UploadImageViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UIAlertViewDelegate>
@property (nonatomic,weak) IBOutlet UIButton *uploadBtn;
@property (nonatomic,weak) IBOutlet UILabel *titleLab;
@property (nonatomic,weak) IBOutlet UICollectionView *imageCollectV;

@property (strong, nonatomic) UIImagePickerController *imagePC;

@property (nonatomic,strong) NSMutableArray *imageArray;
@property (nonatomic,strong) NSMutableArray *imageDataArray;

@property (nonatomic,assign) NSInteger imageNum;
@property (nonatomic,assign) NSInteger uploadPos;
@property (nonatomic,assign) NSInteger startPos;

@property (nonatomic,strong) NSString *fileName;
@property (nonatomic,assign) NSInteger delNum;

@property (nonatomic,strong) NSMutableArray *realUploadImgUrlArray;
@end

@implementation UploadImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"页面加载了");

    self.delNum = -1;
    [self.navigationItem setTitle:@"上传项目资料"];
    self.imageDataArray = [NSMutableArray array];
    self.realUploadImgUrlArray = [NSMutableArray array];
    self.imageArray = [NSMutableArray array];
    self.uploadBtn.layer.cornerRadius = 15;
    
    self.imageCollectV.dataSource = self;
    self.imageCollectV.delegate = self;
    [self.uploadBtn addTarget:self action:@selector(UploadImage) forControlEvents:UIControlEventTouchUpInside];

    self.imageNum = [self.imageUrlArray count];
    NSLog(@"一开始有%ld个图片",[self.imageUrlArray count]);
    self.startPos = [self.imageUrlArray count];
    self.uploadPos = self.startPos;
    [self.realUploadImgUrlArray addObjectsFromArray:self.imageUrlArray];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    switch (self.documentTypeName) {
        case BaseInfo:
            self.titleLab.text = @"请上传基础信息图片";
            break;
        case BusinessConditionsInfo:
            self.titleLab.text = @"请上传经验情况材料图片";
            break;
        case CreditProof:
            self.titleLab.text = @"请上传征信证明图片";
            break;
        case AssetProof:
            self.titleLab.text = @"请上传财力证明图片";
            break;
        case AssetPropertyProof:
            self.titleLab.text = @"请上传财力产权证明图片";
            break;
        case FinanceReportInfo:
            self.titleLab.text = @"请上传财务报表材料图片";
            break;
        case RelevantLawInfo:
            self.titleLab.text = @"请上传相关法律材料图片";
            break;
        case OtherAddInfo:
            self.titleLab.text = @"请上传其他补充材料图片";
        default:
            break;
    }
 
}

#pragma mark - custom method
-(void)UploadImage
{
    if ([self.imageDataArray count] < 1) {
        [GUATool showDialog:@"请添加图片" message:nil waitingTime:1.5];
    }else{
        NSLog(@"%ld",[self.imageUrlArray count]);
        NSLog(@"pos=%ld",self.uploadPos);
        NSLog(@"self.imagedataArray=%ld,self.imageurlarray=%ld",self.uploadPos-self.startPos,self.uploadPos);
        NSString *fileName =[self.imageUrlArray[self.uploadPos] componentsSeparatedByString:@"/"].lastObject;
        [KJSRequest mobileUploadFileWithUploadedFile:self.imageDataArray[self.uploadPos-self.startPos] _uploadedFile_fileName:fileName  documentType:[NSString stringWithFormat:@"%ld",self.documentTypeName] ret:^(ImageUploadModel *model) {
            NSLog(@"model=%@",model);
            if (model.success) {
                [self.imageIdArray addObject:model.result];
                [self.realUploadImgUrlArray addObject:self.imageUrlArray[self.uploadPos]];
                self.uploadFinish(self.realUploadImgUrlArray,self.imageIdArray);
                self.uploadPos = self.uploadPos + 1;
                NSLog(@"后%@",self.imageIdArray);
                if (self.uploadPos == [self.imageUrlArray count]) {
                    [GUATool showDialog:@"文件上传成功" message:nil waitingTime:1.5];
                    NSLog(@"imageurlarray=%ld",[self.imageUrlArray count]);
                    [self dismiss:YES];
                }else{
                    [self UploadImage];
                }
            }
        }];
    }
    
}
-(void)addImage
{
    NSLog(@"到这里了");
    self.imagePC = [[UIImagePickerController alloc] init];
    [self.imagePC setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    self.imagePC.delegate = self;
    [self presentViewController:self.imagePC animated:YES completion:nil];
    
}

- (NSData *)dataWithImage:(UIImage *)image {
    NSData* imageData=UIImageJPEGRepresentation(image, 0.6);
    if (imageData == nil) {
        return UIImagePNGRepresentation(image);
    }
    return imageData;
}
-(void)DeleImage
{
    NSLog(@"delnum=%ld",self.delNum);
    if ([self.imageIdArray count] > self.delNum) {
        NSLog(@"id=%@",self.imageIdArray[self.delNum]);
        [KJSRequest mobileDeleteItemFileWithKjsItemInfoDocumentId:self.imageIdArray[self.delNum] ret:^(BasicResult *model) {
            if (model.success) {
                [GUATool showDialog:@"删除成功" message:nil waitingTime:1.5];
                [self.imageIdArray removeObjectAtIndex:self.delNum];
                [self.imageUrlArray removeObjectAtIndex:self.delNum];
                [self.realUploadImgUrlArray removeObjectAtIndex:self.delNum];
                self.uploadFinish(self.realUploadImgUrlArray,self.imageIdArray);
                self.imageNum = [self.imageUrlArray count];
                [self.imageCollectV reloadData];
            }
        }];
    }else{
        [self.imageUrlArray removeObjectAtIndex:self.delNum];
        self.imageNum = [self.imageUrlArray count];
        [GUATool showDialog:@"删除成功" message:nil waitingTime:1.5];
        [self.imageCollectV reloadData];

    }
    
}
#pragma mark - UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    if (picker == self.imagePC) {
        
        NSURL *assetURL = [info objectForKey:UIImagePickerControllerReferenceURL];
        ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
        [library assetForURL:assetURL resultBlock:^(ALAsset *asset) {
            //获取图片文件名称
            ALAssetRepresentation *imageRep = [asset defaultRepresentation];
            NSLog(@"[imageRep filename] : %@", [imageRep filename]);
            self.fileName = [imageRep filename];
            
            //将图片拷贝到另外目录
            UIImage *image  = [info objectForKey:UIImagePickerControllerOriginalImage];//UIImagePickerControllerEditedImage
            NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
            NSString *documentsDirectory=[paths objectAtIndex:0];
            NSString *savedImagePath=[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",self.fileName]];
            //保存拷贝后的图片url
            NSLog(@"url=%@",savedImagePath);
            [[self dataWithImage:image] writeToFile:savedImagePath atomically:YES];
            [self.imageArray addObject:image];
            [self.imageUrlArray addObject:savedImagePath];
            NSLog(@"现在有%ld个图片",[self.imageUrlArray count]);
            NSLog(@"现在开始的位置=%ld",self.uploadPos);
            [self.imageDataArray addObject:[self dataWithImage:image]];
            self.imageNum = self.imageNum + 1;
            [self.imageCollectV reloadData];
            [picker dismissViewControllerAnimated:YES completion:nil];
        } failureBlock:^(NSError *error) {
            [picker dismissViewControllerAnimated:YES completion:nil];

        }];
        
        
    }
}
#pragma mark - UICollectionViewDatasource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return ([self.imageUrlArray count] + 1);
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //判断是否最后一个cell
    if (indexPath.row == [self.imageUrlArray count]) {
        LastCollectionViewCell *cell = [self.imageCollectV dequeueReusableCellWithReuseIdentifier:@"LastCollectionViewCell" forIndexPath:indexPath];
        [cell.addImageBtn addTarget:self action:@selector(addImage) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }else{
        NSLog(@"imageurl的个数%ld",[self.imageUrlArray count]);
        NSLog(@"id的个数%ld",[self.imageIdArray count]);
        ImageCollectionViewCell * cell = [self.imageCollectV dequeueReusableCellWithReuseIdentifier:@"ImageCollectionViewCell" forIndexPath:indexPath];
        UIImage *imgFromUrl=[[UIImage alloc]initWithContentsOfFile:self.imageUrlArray[indexPath.row]];
        [cell.imageV setImage:imgFromUrl];
        cell.cellNum = indexPath.row;
        if ([self.imageIdArray count] > indexPath.row) {
            NSLog(@"第%ld个的id=%@",indexPath.row,self.imageIdArray[indexPath.row]);
        }
        return cell;
    }
}
#pragma mark - UICollectionViewDelegate
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row != [self.imageUrlArray count]){
        UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"确认删除图片？" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
        self.delNum = indexPath.row;
        [alertV show];
    }
   
}
#pragma mark -UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"buttonIndex=%ld",buttonIndex);
    if (buttonIndex == 1) {
        [self DeleImage];
    }
}
@end
